//
//  HD_NKM_Mediator+Post.m
//  HD_Beacon_Demo
//
//  Created by HDNiuKuiming on 2017/10/28.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HD_NKM_Mediator+Post.h"

#define ScreenWidth [UIScreen mainScreen].bounds.size.width

@implementation HD_NKM_Mediator (Post)

#pragma
#pragma -------- Beacon Data Process --------

// 处理蓝牙收到的号，去除干扰，排序
- (void)sortAndCalculateBeacon:(NSArray *)allBeacons
{
    // 去除干扰号
    NSArray *unknownBeacons = [allBeacons filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"proximity != %d ", CLProximityUnknown]];
    NSMutableArray *unsortedArray = [[NSMutableArray alloc] initWithArray:unknownBeacons];
    // 移除限制号
    for (int i=0; i< unsortedArray.count;i++) {
        CLBeacon *beacon = unsortedArray[i];
        if (beacon.accuracy<0 || beacon.accuracy > self.beaconConfig.ThreshHold_Dis || beacon.minor.integerValue > self.beaconConfig.iBeacon_Num_Max) {
            [unsortedArray removeObject:beacon];
        }
    }
    //    //1、原始排序
    //    NSArray *sortArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(CLBeacon *p1, CLBeacon *p2){
    //        NSString *p1Str = [NSString stringWithFormat:@"%f", p1.accuracy];
    //        NSString *p2Str = [NSString stringWithFormat:@"%f", p2.accuracy];
    //        return [p1Str compare:p2Str];
    //    }];
    
    //2、按距离远近排序，距离近的在前面
//    NSArray *sortArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(CLBeacon *p1, CLBeacon *p2){
//        if (p1.accuracy > p2.accuracy)
//            return NSOrderedDescending;
//        else
//            return NSOrderedAscending;
//    }];
    
    //    // 3、rssi排序
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"rssi" ascending:NO];
        [unsortedArray sortUsingDescriptors:@[sort]];
        NSArray *sortArray = unsortedArray;
    
    [self singleCalculateAction:sortArray]; // 单点
    [self pipeAllBeaconAction:sortArray];   // 抛出全部的排序后的，阈值范围内的beacon
    
    // 处理一段时间未收到号的情况
    if(sortArray.count > 0){
        [self receiveBeaconTime:[NSDate date]];
    }
}

// 单个becon，经过两次收号处理，
- (void)singleCalculateAction:(NSArray *)beaconArray
{
    if (beaconArray.count > 0) {
        CGFloat beaconDis = [self distanceMutiple]; // 根据不同机型，设定不同距离
        if (beaconDis < self.beaconConfig.ThreshHold_Dis)
            beaconDis = self.beaconConfig.ThreshHold_Dis;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            CLBeacon *firstBeacon = nil;
            for (NSInteger i = 0; i < beaconArray.count; i++) {
                CLBeacon *tempBeacon = beaconArray[i];
                if (tempBeacon.accuracy < beaconDis && tempBeacon.minor.integerValue < self.beaconConfig.iBeacon_Num_Max) {
                    firstBeacon = tempBeacon;
                    break;
                }
            }
            
            if (firstBeacon != nil && firstBeacon.minor.integerValue <= self.beaconConfig.iBeacon_Num_Max) {
                [self pipeSingleBeaconNotification:[self pipeBeacon:firstBeacon]];
            }
        });
    }
}

// 单点抛出的是字典类型的，beacon的minor和距离，如果所有的点使用统一个阈值，可以忽略距离参数
- (HD_Beacon_Obj *)pipeBeacon:(CLBeacon *)firstBeacon
{
    NSString *postBeaconStr = nil;
    HD_Beacon_Obj *obj = nil;
    NSString *beaconStr = [NSString stringWithFormat:@"%li",(long)firstBeacon.minor.integerValue];
    if (topBeaconArray.count == 0 ) {
        [topBeaconArray addObject:beaconStr];
        playDis = firstBeacon.accuracy;
    }
    else if (topBeaconArray.count == 1 ) {
        NSString *strA = topBeaconArray[0];
        if (strA.integerValue == beaconStr.integerValue)
        {
            [topBeaconArray addObject:beaconStr];
            postBeaconStr = beaconStr;
            [topBeaconArray removeAllObjects];
            playDis = 0;
        }
        else if (firstBeacon.accuracy < playDis)
        {
            [topBeaconArray removeObjectAtIndex:0];
            [topBeaconArray addObject:beaconStr];
            playDis = firstBeacon.accuracy;
        }
    }
    else {
        playDis = 0;
        [topBeaconArray removeAllObjects];
    }
    
    if (postBeaconStr != nil) {
        obj = [HD_Beacon_Obj new];
        obj.minor = firstBeacon.minor;
        obj.major = firstBeacon.major;
        obj.uuid  = firstBeacon.proximityUUID;
        obj.acc   = [NSString stringWithFormat:@"%f", firstBeacon.accuracy];
        obj.rssi  = [NSString stringWithFormat:@"%ld", (long)firstBeacon.rssi];
    }
    
    return obj;
}

-(void)pipeSingleBeaconNotification:(HD_Beacon_Obj*)postObj
{
    if(postObj != nil) {
        [[NSNotificationCenter defaultCenter] postNotificationName:iBeacon_Send_Notification object:postObj]; // 抛出消息，用于地图定位
    }
}

-(void)pipeAllBeaconAction:(NSArray*)beaconArray
{
    if (beaconArray != nil && beaconArray.count > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:All_iBeacon_Send_Notification object:beaconArray]; // 抛出全部的beacon
        NSMutableArray *tempArr = [NSMutableArray array];
        for (CLBeacon *beacon in beaconArray) {
            NSString  *majorStr = [NSString stringWithFormat:@"%@",beacon.major];
            [tempArr addObject:majorStr];
        }
        if (tempArr.count > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"All_iBeaconMajor_Send_Notification" object:tempArr]; // 抛出全部的beacon
        }
    }
}

#pragma mark
#pragma mark -------- Auto Methods --------

// 机型差异，
- (CGFloat)distanceMutiple
{
    CGFloat dis = self.beaconConfig.ThreshHold_Dis;
    if (ScreenWidth == 320)
        dis = self.beaconConfig.ThreshHold_Dis * 1.5;
    
    return dis;
}

#pragma
#pragma mark -------- Time Methods --------

- (void)receiveBeaconTime:(NSDate *)receiveDate
{
    if (self.beaconConfig.needNoBeaconNoti == YES) {
        noBeaconStartTime       = receiveDate;
        noBeaconEndTime         = receiveDate;
    }
    
    if (self.beaconConfig.needNoBeaconNoti == YES && noBeaconTimer == nil) {
        SEL noBeaconSelector = @selector(postNoBeaconNoti);
        NSRunLoop *currunLoop = [NSRunLoop currentRunLoop];
        noBeaconTimer = [NSTimer timerWithTimeInterval:5 target:self selector:noBeaconSelector userInfo:nil repeats:YES];
        [noBeaconTimer fire];
        [currunLoop addTimer:noBeaconTimer forMode:NSDefaultRunLoopMode];
    }
}

- (void)noBeaconTimerClean
{
    [noBeaconTimer invalidate];
    noBeaconTimer = nil;
}

- (void)cleanBeaconTime
{
    noBeaconStartTime       = nil;
    noBeaconEndTime         = nil;
    [self noBeaconTimerClean];
}

// 在一段时间内没有收到有效的beacon号码，
- (void)postNoBeaconNoti
{
    if (noBeaconStartTime != nil && noBeaconEndTime != nil) {
        // 计算时间差
        NSTimeInterval start = [noBeaconStartTime timeIntervalSince1970]*1;
        NSTimeInterval end   = [[NSDate date] timeIntervalSince1970]*1;
        NSTimeInterval value = end - start;
        NSLog(@"******* time interval is %f", value);
        if (value >= self.beaconConfig.No_Beacon_Last_Time) {
            [[NSNotificationCenter defaultCenter] postNotificationName:No_Beacon_Receive_For_Notification object:nil];
            
            noBeaconStartTime = nil; // 只抛一次消息
            noBeaconEndTime = nil;   // 只抛一次消息
        }
    }
}

@end
